import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:yt_devops/components/app_permission/yt_tab_view_model.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/resources/resources.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/utils/constants/permission_page_constant.dart';
import 'package:yt_devops/utils/constants/store_keys.dart';
import 'package:yt_devops/utils/func_utils.dart';

import '../../../../services/site/site_services.dart';
import '../../../../utils/enums.dart';
import '../siet_elec_price_setting/site_list_view.dart';
import '../siet_elec_price_setting/site_mains_elec_detail/keep_aliver_wrapper.dart';

class MainPriceSettingController extends GetxController
    with GetTickerProviderStateMixin {
  // late TabController tabController;
  bool isShowAdd = true; //是否显示新增按钮
  List<String> allTabs = [
    ResKey.siteSettingElectricityPrice,
    ResKey.siteSettingPhotovoltaicPrice,
    ResKey.siteSettingStoreDischargePrice,
    ResKey.siteSettingChargePrice,
  ];
  // 标题
  String title = ResKey.siteOverviewElectricitySetting.tr;
  bool electricityPermission = true; //市电电价权限
  bool photovoltaicPricePermission = true; //光伏电价权限
  bool storeDischargePricePermission = true; //储能放电电价权限
  bool chargePricePermission = true; //充电电价权限
  List<String> tabs = [];
  List <Widget> tabViews = [];
  GlobalKey<SiteListViewState> mainsKey = GlobalKey<SiteListViewState>();
  GlobalKey<SiteListViewState> internetKey = GlobalKey<SiteListViewState>();
  GlobalKey<SiteListViewState> chargeIdKey = GlobalKey<SiteListViewState>();
  GlobalKey<SiteListViewState> storeKey = GlobalKey<SiteListViewState>();
  final SiteServices siteServices = Get.find<SiteServices>();
  late int siteId;
  var monetaryUnitName = '';
  TextEditingController textController = TextEditingController();
  var energyOptions = '';
  List<YtTabViewModel> permissionGroups = [];
  int selectedIndex = 0;
  @override
  void onInit() {
    if (Get.arguments != null) {
      siteId = Get.arguments['siteId'];
      energyOptions = Get.arguments['energyOptions'];
      if(Get.arguments['monetaryUnitName'] != null){
        monetaryUnitName = Get.arguments['monetaryUnitName'];
      }
    }
    _addTabsAndTableViews();
    super.onInit();
  }
  onItemTapped(index) {
    selectedIndex = index;
    // tabController?.animateTo(index);
    handleTabIndex();
    Log.d('onItemTapped==' + selectedIndex.toString());
    update();
  }
  _addTabsAndTableViews(){
    electricityPermission = FuncUtils.isPassAuthority([PermissionConstant.homeSiteManageSettingElectricitySettingGridAdd]);
    photovoltaicPricePermission = FuncUtils.isPassAuthority([PermissionConstant.homeSiteManageSettingElectricitySettingPvAdd]);
    storeDischargePricePermission = FuncUtils.isPassAuthority([PermissionConstant.homeSiteManageSettingElectricitySettingEssAdd]);
    chargePricePermission = FuncUtils.isPassAuthority([PermissionConstant.homeSiteManageSettingElectricitySettingChargeAdd]);

    YtTabViewModel model1 = YtTabViewModel(permissionString: PermissionConstant.homeSiteManageSettingElectricitySettingGridDetail,
        labelString: allTabs[0],imageString: ImageAssets.siteOverviewDef,
        permissionWidget: SiteListView(
          siteId: siteId,
          key: mainsKey,
          service: siteServices.getSiteMains,
          monetaryUnitName:monetaryUnitName,
          type: $enumDecodeNullable($ElecPriceTypeEnumMap, 0),
          index: 0,
        ));
    YtTabViewModel model2 = YtTabViewModel(permissionString: PermissionConstant.homeSiteManageSettingElectricitySettingPvDetail,
        labelString: allTabs[1],imageString: ImageAssets.siteStatisDataDef,
        permissionWidget: SiteListView(
          siteId: siteId,
          key: internetKey,
          monetaryUnitName:monetaryUnitName,
          service: siteServices.getSiteInternet,
          type: $enumDecodeNullable($ElecPriceTypeEnumMap, 1),
          index: 1,
        ),isShow: energyOptions.contains('1')
    );
    YtTabViewModel model3 = YtTabViewModel(permissionString: PermissionConstant.homeSiteManageSettingElectricitySettingEssDetail,
        labelString: allTabs[2],imageString: ImageAssets.siteDeviceManagerDef,
        permissionWidget: SiteListView(
          siteId: siteId,
          key: storeKey,
          monetaryUnitName:monetaryUnitName,
          service: siteServices.getStoreDischarge,
          type: $enumDecodeNullable($ElecPriceTypeEnumMap, 3),
          index: 3,
        ),isShow: energyOptions.contains('2')
    );
    YtTabViewModel model4 = YtTabViewModel(permissionString: PermissionConstant.homeSiteManageSettingElectricitySettingChargeDetail,
        labelString: allTabs[3],imageString: ImageAssets.siteDetailDef,
        permissionWidget: SiteListView(
          siteId: siteId,
          key: chargeIdKey,
          monetaryUnitName:monetaryUnitName,
          service: siteServices.getSiteCharge,
          type: $enumDecodeNullable($ElecPriceTypeEnumMap, 2),
          index: 2,
        ),isShow: energyOptions.contains('3'));
    permissionGroups.add(model1);
    permissionGroups.add(model2);
    permissionGroups.add(model3);
    permissionGroups.add(model4);
    tabs.clear();
    for (var element in permissionGroups) {
      if(FuncUtils.isPassAuthority([element.permissionString]) && element.isShow) {
        tabs.add(element.labelString.tr);
      }
    }
    handleTabIndex();
}

  handleTabIndex(){
    Log.d('_handleTabIndex===' + tabs.toString());
    if(tabs.isEmpty){
      return;
    }
    if(tabs[selectedIndex] == ResKey.siteSettingElectricityPrice.tr){
      if(electricityPermission){
        isShowAdd = true;
      }else{
        isShowAdd = false;
      }

    }else if(tabs[selectedIndex] == ResKey.siteSettingStoreDischargePrice.tr){
      if(storeDischargePricePermission){
        isShowAdd = true;
      }else{
        isShowAdd = false;
      }
    }else if(tabs[selectedIndex] == ResKey.siteSettingPhotovoltaicPrice.tr){
      if(photovoltaicPricePermission){
        isShowAdd = true;
      }else{
        isShowAdd = false;
      }

    }
    else if(tabs[selectedIndex] == ResKey.siteSettingChargePrice.tr){
      if(chargePricePermission){
        isShowAdd = true;
      }else{
        isShowAdd = false;
      }
    }
    Log.d('isShowAdd===' + isShowAdd.toString());
    // update();
  }
  @override
  void onReady() {
    if(tabs.isNotEmpty){
      handleTabIndex();
    }
  }
  ///新增市电电价,光伏电价.充电桩计费
  addNewElecPriceRule(){
    if(tabs.isEmpty){
      return;
    }
    Log.d('selectedIndex==' + tabs.toString());
    Log.d('selectedIndex==' + tabs[selectedIndex].toString());
    if(tabs[selectedIndex] == ResKey.siteSettingElectricityPrice.tr){//新增市电电价
      Get.toNamed(RouterPath.addMainsElectricityPrice,arguments: siteId)?.then((value){
        if(value ==true){
          refreshMains();
        }
      });
    }else if(tabs[selectedIndex] == ResKey.siteSettingStoreDischargePrice.tr){//储能用电电价
      Log.d('siteSettingStoreDischargePrice==' + tabs[selectedIndex].toString());
      Map<String,dynamic> arguments = {'siteId': siteId,'isEnableEdit':true};
      Get.toNamed(RouterPath.energyStoreageDischargePriceController,arguments: arguments)?.then((value){
        Log.d('==value==' + value.toString());
        if(value ==true){
          refreshStoreEnergy();
        }
      });
    }else if(tabs[selectedIndex] == ResKey.siteSettingPhotovoltaicPrice.tr){//新增光伏电价
      Get.toNamed(RouterPath.addPhotovoltaicPriceSet,arguments: siteId)?.then((value){
        if(value ==true){
          refreshInternet();
        }
      });
    }else if(tabs[selectedIndex] == ResKey.siteSettingChargePrice.tr){//新增充电桩计费
      Get.toNamed(RouterPath.addChargePriceSet,arguments: siteId)?.then((value){
        if(value ==true){
          refreshCharge();
        }
      });
    }

  }
  Map<String, dynamic> setQueryParam() {
    Map<String, dynamic> extraParam = {
      'siteId': siteId,
      // 'id': keyWord
    };
    return extraParam;
  }

  refreshMains() {
    mainsKey.currentState?.extraParam = setQueryParam();
    mainsKey.currentState?.onRefresh();
  }
  refreshStoreEnergy() {
    storeKey.currentState?.extraParam = setQueryParam();
    storeKey.currentState?.onRefresh();
  }
  refreshInternet() {
    internetKey.currentState?.extraParam = setQueryParam();
    internetKey.currentState?.onRefresh();
  }

  refreshCharge() {
    chargeIdKey.currentState?.extraParam = setQueryParam();
    chargeIdKey.currentState?.onRefresh();
  }

  @override
  void onClose() {
    textController.dispose();

  }


}
